package com.study.person.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.study.person.bean.PersonInfo;
import com.study.util.HibernateUtil;

public class PersonDao {

	public static void main(String[] args) {
		try {
			// Configuration configuration = new Configuration().configure();
			// SessionFactory sessionFactory =
			// configuration.buildSessionFactory();
			// Session session = sessionFactory.openSession();
			// Transaction transaction = session.beginTransaction();
			// PersonInfo info = new PersonInfo();
			// info.setId("21111");
			// info.setName("hibernate test");
			// info.setAge(18);
			// info.setSex("1");
			// System.out.println("------------start-------------");
			// session.save(info);
			// System.out.println("-------------end-------------");
			// session.flush();
			// transaction.commit();
			// session.close();

			// 增删改查
			
			
			

			PersonInfo test = new PersonInfo();
			test.setId("1");
			test.setName("hibernate test");
			test.setAge(18);
			test.setSex("1");
			// save(test);

			test.setName("xxxxxx");
			// update(test);
			//
			//
			PersonInfo test2 = queryEntryById("1");
			System.out.println(test2);

			System.out.println("====================");
			List<PersonInfo> list = queryAll();
			for (PersonInfo pInfo : list)
				System.out.println(pInfo);

			System.out.println("====================");
			List<PersonInfo> names = queryLikeName("Jack");
			for (PersonInfo pInfo : names)
				System.out.println(pInfo);

			System.out.println("========QBC============");
			test2 = qbcQueryEntryById("1");
			System.out.println(test2);
			System.out.println("========QBC============");
			list = qbcQueryAll();
			for (PersonInfo pInfo : list)
				System.out.println(pInfo);

			System.out.println("========QBC Other Demo============");
			list = qbcQuerytTest();
			for (PersonInfo pInfo : list)
				System.out.println(pInfo);

			System.out.println("========QBE============");
			list = qbeQuerytTest();
			for (PersonInfo pInfo : list)
				System.out.println(pInfo);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void save(PersonInfo info) {
		if (info == null)
			return;
		Session session = HibernateUtil.currentSession();
		Transaction transaction = session.beginTransaction();
		session.save(info);
		transaction.commit();
		HibernateUtil.closeSession();
	}

	public static void update(PersonInfo info) {
		if (info == null || info.getId() == null)
			return;
		Session session = HibernateUtil.currentSession();
		session.update(info);
		session.flush();
		HibernateUtil.closeSession();
	}

	public static void saveOrUudate(PersonInfo info) {
		if (info == null)
			return;
		Session session = HibernateUtil.currentSession();
		session.update(info);
		session.flush();
		HibernateUtil.closeSession();
	}

	public static void delete(PersonInfo info) {
		if (info == null || info.getId() == null)
			return;
		Session session = HibernateUtil.currentSession();
		session.delete(info);
		session.flush();
		HibernateUtil.closeSession();
	}

	// Hibernate三种查询方式 1 hql 2 qbc《qbe --- query by example》 3 sql
	// hql========================================================
	public static PersonInfo queryEntryById(String id) {
		PersonInfo info = null;
		Session session = HibernateUtil.currentSession();
		Query query = session.createQuery("from PersonInfo pi where pi.id=?");
		query.setString(0, id);

		// 也可以使用冒号
		// Query query =
		// session.createQuery(" from Person p where name=:xxx");//
		// from后面跟的是PO对象名，而不是表名
		// query.setString("xxx", "ttt");

		List<PersonInfo> infos = query.list();
		if (!infos.isEmpty())
			return infos.get(0);
		return info;

	}

	public static List<PersonInfo> queryAll() {
		Session session = HibernateUtil.currentSession();
		Query query = session.createQuery("from PersonInfo");
		List<PersonInfo> list = query.list();
		HibernateUtil.closeSession();
		return list;
	}

	public static List<PersonInfo> queryLikeName(String name) {
		Session session = HibernateUtil.currentSession();
		Query query = session
				.createQuery("from PersonInfo pi where pi.name like :name");
		query.setString("name", "%" + name + "%");
		List<PersonInfo> list = query.list();
		HibernateUtil.closeSession();
		return list;
	}

	// QBC 标志sql查询
	public static PersonInfo qbcQueryEntryById(String id) {
		Session session = HibernateUtil.currentSession();
		Criteria criteriaQuery = session.createCriteria(PersonInfo.class);
		criteriaQuery.add(Restrictions.idEq(id));
		List<PersonInfo> infos = criteriaQuery.list();
		if (!infos.isEmpty())
			return infos.get(0);
		HibernateUtil.closeSession();
		return null;
	}

	public static List<PersonInfo> qbcQueryAll() {
		Session session = HibernateUtil.currentSession();
		Criteria criteriaQuery = session.createCriteria(PersonInfo.class);
		List<PersonInfo> infos = criteriaQuery.list();
		HibernateUtil.closeSession();
		return infos;
	}

	/**
	 * QBC增加其他条件和排序 Demo
	 * 
	 * @return
	 * @return List<PersonInfo>
	 * @Author: TDW
	 * @Date: 2015年6月9日 下午10:36:44
	 * @ModifyUser：TDW
	 * @ModifyDate: 2015年6月9日 下午10:36:44
	 */
	public static List<PersonInfo> qbcQuerytTest() {

		Session session = HibernateUtil.currentSession();
		Criteria criteriaQuery = session.createCriteria(PersonInfo.class);
		criteriaQuery.addOrder(Order.asc("id"));// 根据ID排序
		Map<String, String> conditionMap = new HashMap<String, String>();
		conditionMap.put("name", "hibernate test");// filder,value
		// conditionMap.put("id", "1");
		criteriaQuery.add(Restrictions.allEq(conditionMap));
		// criteriaQuery.add(Restrictions.ilike("name", "hibernate"));
		// criteriaQuery.add(Restrictions.isEmpty("address"));//为空，不是null
		criteriaQuery.add(Restrictions.isNull("address"));
		// criteriaQuery.add(Restrictions.between("age", 18, 30));//age在18到30之间的
		criteriaQuery
				.add(Restrictions.or(
						// or语句使用，年龄是18~30之间或者年龄为null的
						Restrictions.between("age", 18, 30),
						Restrictions.isNull("age")));

		List<PersonInfo> infos = criteriaQuery.list();

		HibernateUtil.closeSession();

		// #######Detached二者的区别就是DetachedCriteria可以离线操作，而Criteria不可以
		DetachedCriteria dc = DetachedCriteria.forClass(PersonInfo.class);
		dc.add(Restrictions.eq("name", "hibernate test"));
		List<PersonInfo> list = dc.getExecutableCriteria(
				HibernateUtil.currentSession()).list();
		for (PersonInfo p : list) {
			System.out.println("-----" + p.getId());
		}

		return infos;
	}

	public static List<PersonInfo> qbeQuerytTest() {

		Session session = HibernateUtil.currentSession();
		PersonInfo p = new PersonInfo();
		p.setName("hibernate test");
		Example example = Example.create(p);

		example.excludeZeroes();
		example.enableLike(MatchMode.ANYWHERE);// 匹配模式,使用模糊查询必填项。
		example.excludeNone();// 空的不做查询条件
		example.excludeZeroes();// 0不要查询
		example.ignoreCase(); // 不区分大小写

		Criteria criteria = session.createCriteria(PersonInfo.class).add(example);
		List<PersonInfo> list = criteria.list();
//		for (PersonInfo p1 : list)
//			System.out.println(p1.getName());

		return list;
	}

}
